package com.pmt.feedplayer.AppNavigation

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.List
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.pmt.feedplayer.data.VideoListState
import com.pmt.feedplayer.ui.AudioPlayerScreen
import com.pmt.feedplayer.ui.AudioPlayerViewModel
import com.pmt.feedplayer.ui.VideoFeed
import com.pmt.feedplayer.ui.VideoListViewModel
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 视频标签页内容
 */
@Composable
fun VideoTabContent(
    viewModel: VideoListViewModel
) {
    val context = LocalContext.current
    val hasPermission = remember {
        ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
    }

    if (!hasPermission) {
        Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(text = "请授予应用访问存储权限")
            Spacer(modifier = Modifier.height(16.dp))
            Text(
                text = "重新授权",
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.clickable {
                    if (context is Activity) {
                        ActivityCompat.requestPermissions(
                            context,
                            arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                            1001
                        )
                    }
                }
            )
        }
    } else {
        VideoFeed(
            videos = VideoListState.Success(emptyList()),
            onVideoClick = { /* 暂时不处理点击事件 */ },
            onLoadMore = {}
        )
    }
}

/**
 * 音频标签页内容
 */
@Composable
fun AudioTabContent(audioPlayerViewModel: AudioPlayerViewModel) {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val listState = rememberLazyListState()
    
    // 模拟音频文件列表
    var audioFiles by remember {
        mutableStateOf(listOf<File>())
    }
    
    // 加载状态
    var isLoading by remember {
        mutableStateOf(true)
    }
    
    // 加载音频文件
    remember {
        coroutineScope.launch {
            try {
                // 模拟从外部存储加载音频文件
                val externalFilesDir = context.getExternalFilesDirs(null).firstOrNull()
                val audioDir = externalFilesDir?.let { File(it, "extracted_audio") }
                
                if (audioDir?.exists() == true) {
                    audioFiles = audioDir.listFiles { file ->
                        file.isFile && file.extension.lowercase() in listOf("mp3", "aac", "m4a")
                    }?.toList() ?: emptyList()
                }
                
                // 如果没有提取的音频文件，创建一些模拟数据
                if (audioFiles.isEmpty()) {
                    audioFiles = listOf(
                        createMockAudioFile("样本音频 1", "2024-01-15"),
                        createMockAudioFile("视频分离音频", "2024-01-10"),
                        createMockAudioFile("会议录音", "2024-01-05")
                    )
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                isLoading = false
            }
        }
    }
    
    // 主内容区域
    Box(modifier = Modifier.fillMaxSize()) {
        // 音频列表
        Column(modifier = Modifier.fillMaxSize()) {
            if (isLoading) {
                Column(
                    modifier = Modifier.fillMaxSize(),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(text = "加载中...")
                }
            } else {
                if (audioFiles.isEmpty()) {
                    Column(
                        modifier = Modifier.fillMaxSize(),
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = "信息图标",
                            modifier = Modifier
                                .height(64.dp)
                                .padding(bottom = 16.dp)
                        )
                        Text(text = "暂无提取的音频文件")
                        Text(text = "从视频标签页提取音频后将在此显示")
                    }
                } else {
                    LazyColumn(
                        modifier = Modifier.fillMaxSize(),
                        state = listState
                    ) {
                        items(audioFiles) { file ->
                            AudioItem(
                                fileName = file.nameWithoutExtension,
                                fileDate = getFileDate(file),
                                onClick = {
                                    // 点击音频项，开始播放
                                    audioPlayerViewModel.playAudio(file)
                                }
                            )
                        }
                    }
                }
            }
        }
        
        // 当showPlayer为true时，显示音频播放页面
        if (audioPlayerViewModel.showPlayer.value == true && audioPlayerViewModel.currentAudioFile.value != null) {
            audioPlayerViewModel.currentAudioFile.value?.let { audioFile ->
                AudioPlayerScreen(
                    audioFile = audioFile,
                    viewModel = audioPlayerViewModel,
                    onClose = { audioPlayerViewModel.closePlayer() }
                )
            }
        }
    }
}

/**
 * 音频列表项
 */
@Composable
fun AudioItem(fileName: String, fileDate: String, onClick: () -> Unit) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
            .clickable(onClick = onClick)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = Icons.Default.List,
                contentDescription = "音频图标",
                modifier = Modifier
                    .padding(end = 16.dp)
            )
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = fileName,
                    fontWeight = FontWeight.Bold
                )
                Text(
                    text = fileDate,
                    fontSize = MaterialTheme.typography.bodySmall.fontSize
                )
            }
        }
    }
}

/**
 * 设置标签页内容
 */
@Composable
fun SettingsTabContent(viewModel: VideoListViewModel) {
    // 本地状态用于设置
    var darkMode by remember { mutableStateOf(false) }
    var enableAudioExtraction by remember { mutableStateOf(true) }
    var enableTranslation by remember { mutableStateOf(false) }
    
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp)
    ) {
        item {
            SectionTitle(text = "外观")
            SettingItem(
                title = "深色模式",
                description = "启用深色主题",
                value = darkMode,
                onValueChange = { darkMode = it }
            )
            Spacer(modifier = Modifier.height(24.dp))
        }
        
        item {
            SectionTitle(text = "功能")
            SettingItem(
                title = "音频提取",
                description = "允许从视频中提取音频",
                value = enableAudioExtraction,
                onValueChange = { enableAudioExtraction = it }
            )
            SettingItem(
                title = "视频翻译",
                description = "启用视频字幕翻译功能",
                value = enableTranslation,
                onValueChange = { enableTranslation = it }
            )
            Spacer(modifier = Modifier.height(24.dp))
        }
        
        item {
            SectionTitle(text = "关于")
            AboutItem(title = "版本", value = "1.0.0")
            AboutItem(title = "开发者", value = "FeedPlayer 团队")
            AboutItem(title = "开源协议", value = "MIT")
        }
    }
}

/**
 * 区域标题
 */
@Composable
fun SectionTitle(text: String) {
    Text(
        text = text,
        fontWeight = FontWeight.Bold,
        fontSize = MaterialTheme.typography.headlineSmall.fontSize,
        modifier = Modifier.padding(bottom = 8.dp)
    )
}

/**
 * 设置项
 */
@Composable
fun SettingItem(
    title: String,
    description: String,
    value: Boolean,
    onValueChange: (Boolean) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(text = title)
            Text(
                text = description,
                fontSize = MaterialTheme.typography.bodySmall.fontSize,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
        Switch(
            checked = value,
            onCheckedChange = onValueChange
        )
    }
}

/**
 * 关于项
 */
@Composable
fun AboutItem(title: String, value: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = title)
        Text(
            text = value,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

// 辅助函数：创建模拟音频文件
private fun createMockAudioFile(name: String, dateString: String): File {
    return File(name)
}

// 辅助函数：获取文件日期
private fun getFileDate(file: File): String {
    return try {
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        sdf.format(Date(file.lastModified()))
    } catch (e: Exception) {
        "未知日期"
    }
}